/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.web.common.util;

import org.apache.commons.lang.StringUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * cookie操作相关的工具类
 *
 * @author yoara
 */
public class CookieUtil {

    public static Cookie getCookie(HttpServletRequest request, String cookieName){
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            for (Cookie cookie : cookies){
                if (cookieName.equals(cookie.getName())){
                   return cookie;
                }
            }
        }
        return null;
    }
    
    public static Cookie addCookie(HttpServletResponse resp
            ,String cookieName,String cookieValue,int second){
        return addCookie(resp,cookieName,cookieValue,null,null,second);
    }

    public static Cookie addCookie(HttpServletResponse resp
            ,String cookieName,String cookieValue,String domain,int second){
        return addCookie(resp,cookieName,cookieValue,domain,null,second);
    }

    public static Cookie addCookie(HttpServletResponse resp
            ,String cookieName,String cookieValue,String domain,String path,int second){
        Cookie ck = new Cookie(cookieName,cookieValue);
        ck.setMaxAge(second);
        if(StringUtils.isNotEmpty(domain)){
            ck.setDomain(domain);
        }
        if(StringUtils.isNotEmpty(path)){
            ck.setPath(path);
        }
        resp.addCookie(ck);
        return ck;
    }
}
